package com.xmqian.app.project.ui.user.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.AppCompatImageView;

import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.coszero.utilslibrary.utils.LogX;
import com.coszero.utilslibrary.utils.ResourceUtils;
import com.coszero.utilslibrary.utils.StringUtils;
import com.coszero.utilslibrary.utils.ToastUtils;
import com.xmqian.app.R;
import com.example.common.base.mvp.BaseMvpActivity;
import com.example.common.config.user.UserManager;
import com.xmqian.app.project.ui.main.MainActivity;
import com.xmqian.app.project.event.LoginEvent;
import com.xmqian.app.project.ui.user.contract.LoginContract;
import com.xmqian.app.project.ui.user.model.LoginModel;
import com.xmqian.app.project.ui.user.presenter.LoginPresenter;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Desc： 普通账号密码登录
 * <p>
 * Author： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/9/20 16:10
 */
public class LoginActivity extends BaseMvpActivity<LoginPresenter> implements LoginContract.View {
    @BindView(R.id.btn_login)
    Button mBtnLogin;
    @BindView(R.id.et_user)
    EditText mEtUser;
    @BindView(R.id.et_pwd)
    EditText mEtPwd;
    @BindView(R.id.iv_toggle_pwd_display)
    AppCompatCheckBox mIvTogglePwdDisplay;
    @BindView(R.id.ll_quik_login)
    ViewGroup mLlQuikLogin;
    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            setLoginBtnState();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    /**
     * 如果顶部刚好有该页面，则使用该页面，如果没有则创建，适用于推送广播创建
     */
    public static void startNewTask(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 单例开启页面，如果堆栈中有，则从底部将页面拉上次，上面的页面全部销毁
     */
    public static void startTask(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setShowBack(false);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected LoginPresenter getPresenter() {
        return new LoginPresenter(this);
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        setTitle("密码登录");
        mEtPwd.addTextChangedListener(textWatcher);
        mEtUser.addTextChangedListener(textWatcher);
        mIvTogglePwdDisplay.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mEtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                mEtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            mEtPwd.setSelection(mEtPwd.getText().toString().length());
        });
        addQuikLogin();
    }

    @Override
    protected void initData() {
    }

    private void setLoginBtnState() {
        if (checkUserInput()) {
            mBtnLogin.setEnabled(true);
        } else {
            mBtnLogin.setEnabled(false);
        }
    }

    private boolean checkUserInput() {
        //校验账号密码
        return !StringUtils.isEmpty(mEtUser.getText().toString()) && mEtPwd.length() >= 4;
    }

    private void addQuikLogin() {
        if (mLlQuikLogin != null) {
            AppCompatImageView imageView = new AppCompatImageView(mActivity);
            imageView.setImageResource(R.drawable.ic_sl_weixin);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins((int) ResourceUtils.getDimension(this, R.dimen.dp_45), 0, 0, 0);
            imageView.setLayoutParams(layoutParams);
            imageView.setOnClickListener(v -> {
                //点击启动微信登录程序
                ToastUtils.showMsg("启动微信中请稍后");
            });
            mLlQuikLogin.addView(imageView);
        }
    }

    @OnClick({R.id.tv_register, R.id.tv_forget_pwd, R.id.btn_login, R.id.tv_quick_login})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_register://注册
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            case R.id.tv_forget_pwd://忘记密码
                startActivity(new Intent(this, ForgetPwdActivity.class));
                break;
            case R.id.tv_quick_login://快捷登录
                startActivity(new Intent(this, QuickLoginActivity.class));
                break;
            case R.id.btn_login://登录
                String userName = mEtUser.getText().toString();
                String password = mEtPwd.getText().toString();
                mPresenter.doLogin(userName, password);
                break;
        }
    }

    // <editor-fold desc="请求回调" defaultstate="collapsed">
    @Override
    public void onLoginSucceed(LoginModel data) {
        LogX.i("登录成功");
//        ToastUtils.showLongMsg(message);
        UserManager userManager = UserManager.getInstance();
        userManager.saveLoginData(data.getUserName(), data.getHeadImage(), data.getToken());
        MainActivity.startActivity(mActivity);
        EventBus.getDefault().post(new LoginEvent(true));
        finish();
    }

    @Override
    public void onRequestFailed(String message) {
        ToastUtils.showLongMsg(message);
    }

    @Override
    public void getCodeSuccess() {

    }

    @Override
    public void onNetworkError() {

    }
    //</editor-fold>
}
